package pers.ljf.escloud.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.web.bind.annotation.*;
import pers.ljf.escloud.common.dto.AppLoginUserInfo;
import pers.ljf.escloud.controller.BaseController;
import pers.ljf.escloud.dao.entity.app.User;
import pers.ljf.escloud.dao.entity.app.UserToken;
import pers.ljf.escloud.dto.SysLoginForm;
import pers.ljf.escloud.service.dto.Result;
import pers.ljf.escloud.service.modules.app.DepartmentService;
import pers.ljf.escloud.service.modules.app.EnterpriseService;
import pers.ljf.escloud.service.modules.app.UserService;
import pers.ljf.escloud.service.modules.sys.SysCaptchaService;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Slf4j
@RequestMapping("/app/user")
@RestController
public class AppLoginController extends BaseController {

    @Resource
    private UserService userService;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private SysCaptchaService captchaService;

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = captchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request,HttpServletResponse response, @RequestBody SysLoginForm form) throws IOException {
        HttpSession session = request.getSession();
        //用户信息
        User user = userService.queryByUserName(form.getUsername());

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return Result.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 1) {
            return Result.error("账号已被锁定,请联系管理员");
        }
        //生成token，并保存到数据库
        Long id = user.getId();
        UserToken token = userService.createToken(id);
        AppLoginUserInfo userInfo = userService.getUserDetailInfo(user);
        userInfo.setToken(token.getToken());
        session.setAttribute("userInfo", userInfo);
        session.setAttribute("token",token.getToken());
        Long entId = user.getEntId();
        //cookie
        Cookie cookie = new Cookie("token", token.getToken());
        cookie.setMaxAge(token.getAge());
        cookie.setPath("/");
        response.addCookie(cookie);
        return Result.ok().put("entId", entId);
    }


    /**
     * 退出
     */
    @PostMapping("/logout")
    public Result logout() {
        userService.logout(getUserId());
        return Result.ok();
    }

    @GetMapping("/info")
    public Result getInfo(@RequestParam String username){
        User operateUser = (User) SecurityUtils.getSubject().getPrincipal();
        User user = userService.getOne(new QueryWrapper<User>().eq("username",username).eq("ent_id",operateUser.getEntId()));
        return Result.ok().put("user",user);
    }
}
